package com.pxx.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxx.item.mapper.CategoryMapper;
import com.pxx.item.pojo.Category;
import com.pxx.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> queryCategoryListByParentId(Long pid) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        List<Category> list = categoryMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Void> add(Category category) {
        int insert = categoryMapper.insert(category);
        if(insert>0){
            System.out.println("添加Id"+category.getId());
            List<Category> list = categoryMapper.selectList(
                    new QueryWrapper<Category>().lambda().eq(Category::getParentId, category.getId())
            );
            if(list.isEmpty()){
                category.setIsParent(true);
                categoryMapper.updateById(category);
            }
        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Void> edit(Category category) {
        Category category1 = categoryMapper.selectById(category.getId());
        category1.setName(category.getName());
        categoryMapper.updateById(category1);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Void> delete(Long id) {
        Category category = categoryMapper.selectById(id);
        List<Category> list = categoryMapper.selectList(new QueryWrapper<Category>().lambda().eq(Category::getParentId, id));
        if(list.isEmpty()){
            categoryMapper.deleteById(category.getId());
        }else{
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
